import { ElMessage } from 'element-plus'
import http from '@/http/http'
import { store } from '@/store'
//递归 查数组里面的对象是否包含 t[key] === nameKey
export const FunArrBool = (arr: [], key: string, nameKey: string) => {
  let flag = false
  const recursionFun = (arr: [], key: string, nameKey: string) => {
    arr.forEach((t: any) => {
      if (t[key] === nameKey) {
        flag = true
      }
      if (t?.children?.length > 0 && !flag) {
        //递归
        recursionFun(t.children, key, nameKey)
      }
    })
  }
  recursionFun(arr, key, nameKey)
  return flag;
}
// 调接口 不需要处理接口返回结果 可以提示成功信息
//第一个参数是接口方法   第二个是接口地址  第三个是传参，
//第四个是是否显示加载  第五个是是否展示接口成功信息和提示内容 第六个是是否刷新表格
export const FunApi = async (get: string, url: string, params?: any, loading?: boolean, msg?: string, refresh?: boolean) => {
  try {
    if (loading) {//是否显示加载状态
      store.commit('loading/setLoad', true)
    }
    let res = await http[get](url, params)
    if (res?.code === 0) {
      if (msg) {
        //成功的提示信息
        ElMessage({ type: 'success', message: `${msg}成功` })
      }
      if (refresh) {
        //是否表格刷新
        store.commit('refresh/setRefresh', !store.getters['refresh/getRefresh'])
      }
    }
    if (loading) {//接口完成 取消加载状态
      store.commit('loading/setLoad', false)
    }
  } catch {
    if (loading) {//接口失败 取消加载状态
      store.commit('loading/setLoad', false)
    }
  }
}
//时间戳格式
export const FunTime = (val:any, style?:string) => {
  let date = val?new Date(val):new Date()
  let year = date.getFullYear()
  let month = date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)
  let month2 = date.getMonth() + 1
  let week = date.getDay()
  let day = date.getDate() > 9 ? date.getDate() : '0' + date.getDate()
  let day2 = date.getDate()
  let hour = date.getHours() > 9 ? date.getHours() : '0' + date.getHours()
  let minutes = date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes()
  let second = date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds()
  if (style === "YY-MM-DD hh:mm:ss") {
    return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + second
  } else if (style === "YY-MM") {
    return year + '-' + month
  } else if (style === "YY-MM-Zh") {
    return year + '年' + month2 + '月'
  } else if (style === "YY-MM-DD-Zh") {
    return year + '年' + month2 + '月' + day2 + '日'
  } else if(style === 'HH:mm'){
    return hour +':'+ minutes
  } else {
    return year + '-' + month + '-' + day
  }
};

